package cn.etgps.etgps.ui;

import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import cn.etgps.etgps.R;
import cn.etgps.etgps.blmanager.TruckManager;
import cn.etgps.etgps.dataEntity.TrackReplayBean;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.utils.AppUtils;

/**
 * Created by itte on 2015/12/2.
 */
public class MapTruckPlaybackActivity extends MapActivity implements SeekBar.OnSeekBarChangeListener,
        View.OnClickListener {

    private static final int HANDLER_UPDATEUI = 1001;
    private static final int TIME_INTERVAL = 400;
    private static int mStartIndex = 0;
    private static TrackReplayBean mTrackReplayBean = null;
    private int mScreedWidth = 0;
    private int mScreedHeight = 0;
    /**
     * 地图上的线
     */
    private Polyline mPolyline = null;
    /**
     * 绘制地图上的线的选项
     */
    private PolylineOptions mPolylineOptions = null;
    /**
     * 用于在线上移动的marker
     */
    private Marker mMoveMarker = null;
    /**
     * marker的选项
     */
    private MarkerOptions mMarkerOptions = null;
    private TextView mDate = null;
    private TextView mSpeed = null;
    private TextView mDirection = null;
    private TextView mAddress = null;
    private TextView mReserve = null;//备用textview，visible设为gone（隐藏）
    private ImageButton mPlayButton = null;
    private SeekBar mSeekBar = null;
    private boolean isRun = false;
    private TruckPlayBackHandler mHandler = null;
    /**
     * 标记拖动Seekbar结束后是否恢复播放
     */
    private boolean isNeedRun = false;
    /**
     * 存放轨迹回放的数据来源
     */
    private ArrayList<TrackReplayBean> mLoactions = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //add play view  group to map view
        FrameLayout mainMapLayout = (FrameLayout) findViewById(R.id.mapview_main_layout);
        View playViewGroup = this.getLayoutInflater().inflate(R.layout.seek_bar_view, null);
        mainMapLayout.addView(playViewGroup);
        mDate = (TextView) playViewGroup.findViewById(R.id.tv_date);
        mSpeed = (TextView) playViewGroup.findViewById(R.id.tv_speed);
        mDirection = (TextView) playViewGroup.findViewById(R.id.tv_diraction);
        mAddress = (TextView) playViewGroup.findViewById(R.id.tv_address);
        mReserve = (TextView) playViewGroup.findViewById(R.id.tv_reserve);//备用Textview，已隐藏
        mPlayButton = (ImageButton) playViewGroup.findViewById(R.id.btn_play);
        mPlayButton.setOnClickListener(this);
        mSeekBar = (SeekBar) playViewGroup.findViewById(R.id.seek_bar);
        mSeekBar.setOnSeekBarChangeListener(this);
        mHandler = new TruckPlayBackHandler(this);

        mLoactions = TrackReplaySettingActivity.mLoactions;
//        mLoactions = (ArrayList<TrackReplayBean>) getIntent().getSerializableExtra("Location");
        if (mLoactions == null || mLoactions.size() <= 1) {
            TruckManager manager = new TruckManager(this);
            manager.showToastMessage(getString(R.string.toast_content_null), 2000);
            this.finish();
        } else {
            new GetTruckPlaybackDatasTask().execute();
        }
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        mTitlebarView.initTitleBarInfo(getString(R.string.label_map_truck_playback_title), "", R.drawable.icon_return,
                "", 0, false);
        mTitlebarView.setMainClickListener(this, getString(R.string.btn_back), "");
    }

    @Override
    public void clickButtonListener(String name) {
        super.clickButtonListener(name);
        if (name.equals(getString(R.string.btn_back))) {
            this.finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRun = false;
        mStartIndex = 0;
        if (mLoactions != null && mLoactions.size() > 0) {
            mLoactions.clear();
        }
    }

    @Override
    public void onClick(View v) {
        if (!isRun) {
            mPlayButton.setBackgroundResource(R.drawable.pause);
            isRun = true;
        } else {
            isRun = false;
            mPlayButton.setBackgroundResource(R.drawable.play);
        }
        mHandler.sendMessage(mHandler.obtainMessage(HANDLER_UPDATEUI));
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mStartIndex = progress;
            mSeekBar.setProgress(mStartIndex);
            LatLng startPoint = mPolyline.getPoints().get(mStartIndex);
            mMoveMarker.setPosition(startPoint);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (isRun) {
            isRun = false;
            isNeedRun = true;
        } else {
            isNeedRun = false;
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (isNeedRun) {
            isRun = true;
            isNeedRun = false;
            mHandler.sendMessage(mHandler.obtainMessage(HANDLER_UPDATEUI));
        }
    }

    /**
     * 设置地图上线的属性、设置地图缩放按钮的位置、在地图上画线
     */
    private void setUpMap() {
        DisplayMetrics dm = new DisplayMetrics();
        android.view.Display display = getWindowManager().getDefaultDisplay();
        display.getMetrics(dm);
        mScreedWidth = dm.widthPixels;
        mScreedHeight = dm.widthPixels;
        if (dm.widthPixels >= 960) {
            mPolylineOptions.width(32);//设置线的宽度
        } else {
            mPolylineOptions.width(24);
        }
//        mPolylineOptions.color(Color.BLUE);//设置线的颜色
        mPolylineOptions.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.custtexture));
        mPolylineOptions.geodesic(true);
        mPolylineOptions.setDottedLine(false);//true为虚线，false为实线
        mPolylineOptions.visible(true);//true为可见，false为不可见
        //设置地图放大图标位置
        UiSettings uiSettings = mAMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(true);//显示缩放按钮
        uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);//缩放按钮放在屏幕右侧居中
        uiSettings.setTiltGesturesEnabled(false);//设置地图不可倾斜
        // 绘制一条直线
        mPolyline = mAMap.addPolyline(mPolylineOptions);
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mPolylineOptions.getPoints().get(0), 11));
        mAMap.moveCamera(CameraUpdateFactory.scrollBy(0, 100));
        addMarkerToMap();
    }

    /**
     * 将marker放到地图上
     */
    private void addMarkerToMap() {
        //Add start marker
        MarkerOptions startMarker = new MarkerOptions();
        startMarker.position(mPolylineOptions.getPoints().get(0));//位置
        startMarker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_start));
        startMarker.setFlat(true);
        startMarker.anchor(0.5f, 0.5f);
        startMarker.draggable(false);//拖拽
        mMoveMarker = mAMap.addMarker(startMarker);
        //Add end marker
        MarkerOptions endMarker = new MarkerOptions();
        endMarker.position(mPolylineOptions.getPoints().get(mPolylineOptions.getPoints().size() - 1));//位置
        endMarker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_end));
        endMarker.setFlat(true);
        endMarker.anchor(0.5f, 0.5f);
        endMarker.draggable(false);//拖拽
        mMoveMarker = mAMap.addMarker(endMarker);

        //Add truck marker
        LayoutInflater mInflater = LayoutInflater.from(this);
        View view = mInflater.inflate(R.layout.map_mark_view, null);
        view.findViewById(R.id.licence).setVisibility(View.GONE);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(view);
        mMarkerOptions = new MarkerOptions();
        mMarkerOptions.position(mPolylineOptions.getPoints().get(mStartIndex));//位置
        mMarkerOptions.icon(markerIcon);
        mMarkerOptions.setFlat(true);
        mMarkerOptions.anchor(0.5f, 0.5f);
        mMarkerOptions.draggable(false);//拖拽
        mMoveMarker = mAMap.addMarker(mMarkerOptions);
    }

    /**
     * 根据两点算取图标转的角度
     */
    private double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        double angle = 180 * (radio / Math.PI) + deltAngle - 90;
        return angle;
    }

    private double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        double slope = ((toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude));
        return slope;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            clickButtonListener(getString(R.string.btn_back));
        }
        return super.dispatchKeyEvent(event);
    }

    public void checkMarkerPosition() {
        Point point = mAMap.getProjection().toScreenLocation(mMoveMarker.getPosition());
        if (point.x > mScreedWidth || point.y > mScreedHeight || point.x < 0 || point.y < 0) {
            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(mMoveMarker.getPosition()));
        }
    }

    /**
     * process to process communication
     */
    class TruckPlayBackHandler extends Handler {
        WeakReference<MapTruckPlaybackActivity> mActivityReference;

        TruckPlayBackHandler(MapTruckPlaybackActivity activity) {
            mActivityReference = new WeakReference<MapTruckPlaybackActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final MapTruckPlaybackActivity activity = mActivityReference.get();
            if (activity == null) {
                return;
            }
            if (msg.what == HANDLER_UPDATEUI) {
                if (mStartIndex == mPolyline.getPoints().size() - 1) {
                    mSeekBar.setProgress(mStartIndex);
                    isRun = false;
                    mStartIndex = 0;
                    LatLng startPoint = mPolyline.getPoints().get(0);
                    mMoveMarker.setPosition(startPoint);
                    mSeekBar.setProgress(0);
                    mPlayButton.setBackgroundResource(R.drawable.play);
                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mPolylineOptions.getPoints().get(0), 11));
                } else if (isRun) {
                    mTrackReplayBean = mLoactions.get(mStartIndex);
                    mDate.setText(mTrackReplayBean.getGpstime());
                    mSpeed.setText(mTrackReplayBean.getSpeed() + getString(R.string.item_acc_speed_unit));
                    mDirection.setText(getString(R.string.item_btn_direction_info) + AppUtils.getDirectionString(
                            mTrackReplayBean.getDirection()));
                    mAddress.setText(
                            getString(R.string.label_truck_playback_location) + mTrackReplayBean.getLocations());
                    mReserve.setText("备用TextView，已隐藏");
                    LatLng startPoint = mPolyline.getPoints().get(mStartIndex);
                    mMoveMarker.setRotateAngle(
                            (float) getAngle(startPoint, mPolyline.getPoints().get(mStartIndex + 1)));
                    mMoveMarker.setPosition(startPoint);
                    mSeekBar.setProgress(mStartIndex);
                    mStartIndex++;
                    checkMarkerPosition();
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(HANDLER_UPDATEUI), TIME_INTERVAL);
                }
            }
        }
    }

    /**
     * 将TrackBean对象转换成PolyLine上的点
     */
    class GetTruckPlaybackDatasTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            mPolylineOptions = new PolylineOptions();
            TrackReplayBean bean = null;
            for (int i = 0; i < mLoactions.size() - 1; i++) {
                bean = mLoactions.get(i);
                mPolylineOptions.add(new LatLng(bean.getLatitude(), bean.getLongitude()));
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dismissNormalDialog();
            setUpMap();
            mSeekBar.setMax(mPolyline.getPoints().size() - 1);
        }
    }
}
